/**
 * 加载纹理贴图
 * @param {WebGL Object} gl WebGL 对象
 * @param {String} url  纹理贴图url路径
 * @param {String} id  纹理贴图id
 * @param {Function} callback 回调函数
 */
function loadTexture(gl, url, id, callback){
    var image = new Image();
    image.crossOrigin = true;
    image.onload = function(){
        var texture = _loadTexture(gl, image, id);
        callback(texture);
    }
    image.onerror = function(){
        callback(undefined);
        throw new Error("图片加载失败!");
    }
    image.src = url;
}

function _loadTexture(gl, image, id){
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
    // MAG采样
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    // MIN采样
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    // S轴拉伸
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
    // T轴拉伸
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
    gl.bindTexture(gl.TEXTURE_2D, null);
    if(typeof gl.textures === "undefined"){
        gl.textures = {};
    }
    gl.textures[id] = texture;
    return texture;
}



export { loadTexture };